﻿using System.Collections.Generic;
using System.Linq;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using RedDockNet_BackEnd.Config;
using RedDockNet_BackEnd.Model;

namespace RedDockNet_BackEnd.Service
{
    public class UserService : IMongoDBService<User>
    {
        private readonly IMongoCollection<User> users;

        public UserService(IMongoDBConfig config)
        {
            MongoClient client = new MongoClient(config.ConnectionString);
            IMongoDatabase database = client.GetDatabase(config.Database);
            this.users = database.GetCollection<User>(config.Collection);
        }

        public List<User> Select()
        {
            // 需要排除逻辑删除
            List<User> result = (
                from user in this.users.AsQueryable()
                where user.Deleted == false
                select user).ToList();
            return result;
        }

        public User Select(string id)
        {
            // 需要排除逻辑删除
            User result = (
                from user in this.users.AsQueryable()
                where user.ObjectId == id &&
                    user.Deleted == false
                select user).FirstOrDefault();
            return result;
        }
        public void Insert(User user)
        {
            this.users.InsertOne(user);
        }

        public void InsertMany(List<User> users)
        {
            this.users.InsertMany(users);
        }

        public void Update(User user)
        {
            this.users.ReplaceOne(us => us.ObjectId == user.ObjectId, user);
        }

        public void Delete(User user)
        {
            this.users.DeleteOne(us => us.ObjectId == user.ObjectId);
        }

        public void Delete(string id)
        {
            this.users.DeleteOne(us => us.ObjectId == id);
        }
    }
}
